<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/ice.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/ice.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":3,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="二叉树的定义二叉树（Binary Tree） 二叉树（Binary Tree）是有限个节点的集合，这个集合可以是空集，也可以是一个根节点和两颗不相交的子二叉树组成的集合，其中一颗树叫根的左子树，另一颗树叫右子树。所以二叉树是一个递归地概念。">
<meta property="og:type" content="article">
<meta property="og:title" content="二叉树">
<meta property="og:url" content="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91/index.html">
<meta property="og:site_name" content="严冰的博客">
<meta property="og:description" content="二叉树的定义二叉树（Binary Tree） 二叉树（Binary Tree）是有限个节点的集合，这个集合可以是空集，也可以是一个根节点和两颗不相交的子二叉树组成的集合，其中一颗树叫根的左子树，另一颗树叫右子树。所以二叉树是一个递归地概念。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/007S8ZIlgy1gf4f6hekj3j30m80bvab1.jpg">
<meta property="article:published_time" content="2020-05-30T12:50:49.000Z">
<meta property="article:modified_time" content="2020-06-08T00:57:51.991Z">
<meta property="article:author" content="yanbing">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/007S8ZIlgy1gf4f6hekj3j30m80bvab1.jpg">

<link rel="canonical" href="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>二叉树 | 严冰的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="严冰的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">严冰的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/dog.jpg">
      <meta itemprop="name" content="yanbing">
      <meta itemprop="description" content="闲看庭前花开落，漫随天外云卷舒。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="严冰的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          二叉树
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-30 20:50:49" itemprop="dateCreated datePublished" datetime="2020-05-30T20:50:49+08:00">2020-05-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-08 08:57:51" itemprop="dateModified" datetime="2020-06-08T08:57:51+08:00">2020-06-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">数据结构与算法</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="二叉树的定义"><a href="#二叉树的定义" class="headerlink" title="二叉树的定义"></a>二叉树的定义</h2><p><strong>二叉树（Binary Tree）</strong></p>
<p>二叉树（Binary Tree）是有限个节点的集合，这个集合可以是空集，也可以是一个根节点和两颗不相交的子二叉树组成的集合，其中一颗树叫根的左子树，另一颗树叫右子树。所以二叉树是一个递归地概念。</p>
<a id="more"></a>

<p><strong>满二叉树（Full Binary Tree）</strong><br>一棵满二叉树就是高度为k，且拥有<code>(2^k)-1</code>个节点的二叉树，一棵满二叉树每个节点，要么都有两棵子树，要么都没有子树；而且每一层所有的节点之间必须要么都有两棵子树，要么都没子树。</p>
<p><strong>完全二叉树（Complete Binary Tree）</strong><br>完全二叉树是一颗特殊的二叉树，假设完全二叉树高度为k，则完全二叉树需要符合以下两点：</p>
<ol>
<li>所有叶子节点都出现在k层或k-1层，并且从1~k-1层必须达到最大节点数</li>
<li>第k层可以是不满的，但是第k层的所有节点必须集中在最左边</li>
</ol>
<h2 id="二叉树的实现"><a href="#二叉树的实现" class="headerlink" title="二叉树的实现"></a>二叉树的实现</h2><p>二叉树的左右链表表示法：</p>
<img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1gf4f6hekj3j30m80bvab1.jpg" alt="二叉树的左右链表表示法" style="zoom:67%;" />

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BinaryTreeNode</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> data;  <span class="comment">//数据</span></span><br><span class="line">    <span class="keyword">private</span> BinaryTreeNode leftChild ;  <span class="comment">//左孩子</span></span><br><span class="line">    <span class="keyword">private</span> BinaryTreeNode rightChild ; <span class="comment">//右孩子</span></span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getData</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> data;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setData</span><span class="params">(<span class="keyword">int</span> data)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.data = data;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">getLeftChild</span> <span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> leftChild ;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setLeftChild</span> <span class="params">(BinaryTreeNode leftChild )</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.leftChild  = leftChild ;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">getRightChild</span> <span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> rightChild ;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRightChild</span> <span class="params">(BinaryTreeNode rightChild )</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.rightChild  = rightChild ;</span><br><span class="line">    &#125;        </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="二叉树的操作"><a href="#二叉树的操作" class="headerlink" title="二叉树的操作"></a>二叉树的操作</h2><h3 id="遍历"><a href="#遍历" class="headerlink" title="遍历"></a>遍历</h3><h4 id="先根遍历-Pre-Order"><a href="#先根遍历-Pre-Order" class="headerlink" title="先根遍历(Pre Order)"></a>先根遍历(Pre Order)</h4><p>若二叉树为空，则退出，否则进行下面操作：</p>
<ul>
<li>访问根节点</li>
<li>先根遍历左子树</li>
<li>先根遍历右子树</li>
<li>退出</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">PreOrder</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(node != <span class="keyword">null</span>)&#123;</span><br><span class="line">        System.out.println(node.getData()); 	<span class="comment">//先访问根节点</span></span><br><span class="line">        PreOrder(node.getLeftChild ());  		<span class="comment">//先根遍历左子树</span></span><br><span class="line">        PreOrder(node.getRightChild ());  		<span class="comment">//先根遍历右子树</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="中根遍历-In-Order"><a href="#中根遍历-In-Order" class="headerlink" title="中根遍历(In Order)"></a>中根遍历(In Order)</h4><p>若二叉树为空，则退出，否则进行下面操作</p>
<ul>
<li>中根遍历左子树</li>
<li>访问根节点</li>
<li>中根遍历右子树</li>
<li>退出</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">InOrder</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(node != <span class="keyword">null</span>)&#123;</span><br><span class="line">        InOrder(node.getLeftChild());  				<span class="comment">//中根遍历左子树</span></span><br><span class="line">        System.out.println(node.getData());    		<span class="comment">//访问根节点</span></span><br><span class="line">        InOrder(node.getRightChild());  			<span class="comment">//中根遍历右子树</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="后根遍历-Post-Order"><a href="#后根遍历-Post-Order" class="headerlink" title="后根遍历(Post Order)"></a>后根遍历(Post Order)</h4><p>若二叉树为空，则退出，否则进行下面操作</p>
<ul>
<li>后根遍历左子树</li>
<li>后根遍历右子树</li>
<li>访问根节点</li>
<li>退出</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">PostOrder</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(node != <span class="keyword">null</span>)&#123;</span><br><span class="line">        PostOrder(node.getLeftChild());  				<span class="comment">//后根遍历左子树</span></span><br><span class="line">        PostOrder(node.getRightChild());  				<span class="comment">//后根遍历右子树</span></span><br><span class="line">        System.out.println(node.getData());   			<span class="comment">//访问根节点</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="层次遍历-Level-Traverse"><a href="#层次遍历-Level-Traverse" class="headerlink" title="层次遍历(Level Traverse)"></a>层次遍历(Level Traverse)</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">levelTraverse</span><span class="params">(BinaryTreeNode root)</span> </span>&#123;  </span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) &#123;  </span><br><span class="line">        <span class="keyword">return</span>;  </span><br><span class="line">    &#125;  </span><br><span class="line">    LinkedList&lt;BinaryTreeNode&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();  </span><br><span class="line">    queue.offer(root);  </span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;  </span><br><span class="line">        BinaryTreeNode node = queue.poll();  </span><br><span class="line">        System.out.print(node.getData()+<span class="string">"  "</span>);  </span><br><span class="line">        <span class="keyword">if</span> (node.getLeftChild() != <span class="keyword">null</span>) &#123;  </span><br><span class="line">            queue.offer(node.getLeftChild());  </span><br><span class="line">        &#125;  </span><br><span class="line">        <span class="keyword">if</span> (node.getRightChild() != <span class="keyword">null</span>) &#123;  </span><br><span class="line">            queue.offer(node.getRightChild());  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="常用操作"><a href="#常用操作" class="headerlink" title="常用操作"></a>常用操作</h3><h4 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h4><p>创建二叉树，一般有两种情况：初始化一个根节点或者初始化一棵空二叉树。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BinaryTree</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> BinaryTreeNode root;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//初始化二叉树</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BinaryTree</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">BinaryTree</span><span class="params">(BinaryTreeNode root)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.root = root;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setRoot</span><span class="params">(BinaryTreeNode root)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.root = root;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">getRoot</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> root;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="清空"><a href="#清空" class="headerlink" title="清空"></a>清空</h4><p>对于二叉树的清空，首先提供一个清空某个节点为根节点的子树的方法，即递归的删除每个节点；接着提供删除一个删除树的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//清除某个子树的所有节点</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clear</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(node!=<span class="keyword">null</span>)&#123;</span><br><span class="line">        clear(node.getLeftChild());</span><br><span class="line">        clear(node.getRightChild());</span><br><span class="line">        node = <span class="keyword">null</span>; <span class="comment">//删除节点</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">	</span><br><span class="line"><span class="comment">//清空整个树</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clear</span><span class="params">()</span></span>&#123;</span><br><span class="line">    clear(root);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="判断是否为空"><a href="#判断是否为空" class="headerlink" title="判断是否为空"></a>判断是否为空</h4><p>只需判断根节点是否存在即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//判断二叉树是否为空</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isEmpty</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> root == <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="求最大深度-高度"><a href="#求最大深度-高度" class="headerlink" title="求最大深度(高度)"></a>求最大深度(高度)</h4><p>首先需要一种获取以某个节点为子树的高度方法，使用递归实现。如果一个节点为空，那么这个节点肯定是一颗空树，高度为0；如果不为空，则遍历地比较它的左右子树高度，高的一个为这颗子树的最大高度，然后加上自身的高度即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取二叉树的高度</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMaxDepth</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> getMaxDepth(root);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取以某节点为子树的高度</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMaxDepth</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(node == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>; <span class="comment">//递归结束，空子树高度为0</span></span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="comment">//递归获取左子树高度</span></span><br><span class="line">        <span class="keyword">int</span> l = getMaxDepth(node.getLeftChild());</span><br><span class="line">        <span class="comment">//递归获取右子树高度</span></span><br><span class="line">        <span class="keyword">int</span> r = getMaxDepth(node.getRightChild());</span><br><span class="line">        <span class="comment">//高度应该算更高的一边，（+1是因为要算上自身这一层）</span></span><br><span class="line">        <span class="keyword">return</span> l &gt; r ? (l+<span class="number">1</span>) : (r+<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="求最小深度"><a href="#求最小深度" class="headerlink" title="求最小深度"></a>求最小深度</h4><p>根节点到最近叶子结点的距离</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMinDepth</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> getMinDepth (root);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMinDepth</span><span class="params">(BinaryTreeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">null</span> == node) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">null</span> == node.getLeftChild()) &#123;</span><br><span class="line">        <span class="keyword">return</span> getMinDepth(node.getRightChild()) + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">null</span> == root.getRightChild()) &#123;</span><br><span class="line">        <span class="keyword">return</span> getMinDepth(node.getLeftChild()) + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//递归获取左子树高度</span></span><br><span class="line">    <span class="keyword">int</span> l = getMaxDepth(node.getLeftChild());</span><br><span class="line">    <span class="comment">//递归获取右子树高度</span></span><br><span class="line">    <span class="keyword">int</span> r = getMaxDepth(node.getRightChild());</span><br><span class="line">    <span class="comment">//高度应该算更低的一边，（+1是因为要算上自身这一层）</span></span><br><span class="line">    <span class="keyword">return</span> l &lt; r ? (l+<span class="number">1</span>) : (r+<span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="求所有节点数"><a href="#求所有节点数" class="headerlink" title="求所有节点数"></a>求所有节点数</h4><p>获取二叉树节点数，需要获取以某个节点为根的子树的节点数实现。如果节点为空，则个数肯定为0；如果不为空，则算上这个节点之后，继续递归计算所有子树的节点数，全部相加即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">size</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> size(root);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">size</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(node == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;  <span class="comment">//如果节点为空，则返回节点数为0</span></span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="comment">//计算本节点 所以要+1</span></span><br><span class="line">        <span class="comment">//递归获取左子树节点数和右子树节点数，最终相加</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span> + size(node.getLeftChild ()) + size(node.getRightChild ());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="求叶子节点个数"><a href="#求叶子节点个数" class="headerlink" title="求叶子节点个数"></a>求叶子节点个数</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getNumOfChildNode</span><span class="params">(BinaryTreeNode root)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(<span class="keyword">null</span> == root) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span>(<span class="keyword">null</span> == root.getLeftChild() &amp;&amp; <span class="keyword">null</span> == root.RightChild()) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> getNumOfChildNode(root.getLeftChild())+getNumOfChildNode(root.getLeftChild());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="求第k层节点数"><a href="#求第k层节点数" class="headerlink" title="求第k层节点数"></a>求第k层节点数</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">getNumOfLevelNode</span><span class="params">(BinaryTreeNode root, <span class="keyword">int</span> k)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(<span class="keyword">null</span> == root || k &lt; <span class="number">1</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">if</span>(<span class="number">1</span> == k) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> numleft = getNumOfLevelNode(root.getLeftChild(), k - <span class="number">1</span>);</span><br><span class="line">	<span class="keyword">int</span> numright = getNumOfLevelNode(root.RightChild,k - <span class="number">1</span>);</span><br><span class="line">	<span class="keyword">return</span> numleft + numright;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="返回某节点的父亲节点"><a href="#返回某节点的父亲节点" class="headerlink" title="返回某节点的父亲节点"></a>返回某节点的父亲节点</h4><p>首先，同样需要通过一种方法来获取某个节点在某个子树中的父节点，这里使用递归实现，接着通过这种方法获取这个节点在二叉树中的父节点。</p>
<p>事实上，以现有的这种二叉树的形式，我们并没有办法直接获取一个节点的父节点， 这里只能通过从根节点遍历来比较获取。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//node节点在subTree子树中的父节点</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">getParent</span><span class="params">(BinaryTreeNode subTree, BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="comment">//如果是空子树，则没有父节点</span></span><br><span class="line">    <span class="keyword">if</span>(subTree == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;   </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//如果子树的根节点的左右孩子之一是待查节点，则返回子树的根节点</span></span><br><span class="line">    <span class="keyword">if</span>(subTree.getLeftChild () == node || subTree.getRightChild () == node)&#123;</span><br><span class="line">        <span class="keyword">return</span> subTree;   </span><br><span class="line">    &#125;</span><br><span class="line">    BinaryTreeNode parent = <span class="keyword">null</span>;</span><br><span class="line">    <span class="comment">//递归左右子树</span></span><br><span class="line">    <span class="keyword">if</span>(getParent(subTree.getLeftChild (), node) != <span class="keyword">null</span>)&#123;</span><br><span class="line">        parent = getParent(subTree.getLeftChild (), node);</span><br><span class="line">        <span class="keyword">return</span> parent;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> getParent(subTree.getRightChild (), node);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查找node节点在二叉树中的父节点</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">getParent</span><span class="params">(BinaryTreeNode node)</span></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (root == <span class="keyword">null</span> || root == node) ? <span class="keyword">null</span> : getParent(root, node);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="查找节点"><a href="#查找节点" class="headerlink" title="查找节点"></a>查找节点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">findNode</span><span class="params">(BinaryTreeNode root, <span class="keyword">int</span> x)</span></span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(root == <span class="keyword">null</span>)&#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(root.getData() == x)&#123;</span><br><span class="line">		<span class="keyword">return</span> root;</span><br><span class="line">	&#125;</span><br><span class="line">    <span class="comment">//递归搜索左子树</span></span><br><span class="line">	BinaryTreeNode leftNode = findNode(root.getLeftChild(), x);</span><br><span class="line">	<span class="keyword">if</span>(<span class="keyword">null</span> != leftNode)</span><br><span class="line">		<span class="keyword">return</span> leftNode;</span><br><span class="line">    <span class="comment">//递归搜索右子树</span></span><br><span class="line">	BinaryTreeNode rightNode = findNode(root.getRightChild(), x);</span><br><span class="line">	<span class="keyword">if</span>(<span class="keyword">null</span> != rightNode)</span><br><span class="line">		<span class="keyword">return</span> rightNode;</span><br><span class="line">    <span class="comment">//没找到，返回null</span></span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="判断两棵二叉树是否相等"><a href="#判断两棵二叉树是否相等" class="headerlink" title="判断两棵二叉树是否相等"></a>判断两棵二叉树是否相等</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isEquals</span><span class="params">(BinaryTreeNode root1, BinaryTreeNode root2)</span></span>&#123;</span><br><span class="line">    <span class="comment">//当前节点均为空或者相等，返回true</span></span><br><span class="line">    <span class="keyword">if</span>((root1 == <span class="keyword">null</span> &amp;&amp; root2 == <span class="keyword">null</span>) ||root1.getData() == root2.getData())&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//递归判断所有左右子树，均相等返回true</span></span><br><span class="line">    <span class="keyword">if</span>(isEquals(root1.getLeftChild(), root2.getLeftChild()) </span><br><span class="line">       &amp;&amp; isEquals(root1.getRightChild(), root2.getRightChild()))&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//否则返回false</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="判断两棵二叉树是否镜像"><a href="#判断两棵二叉树是否镜像" class="headerlink" title="判断两棵二叉树是否镜像"></a>判断两棵二叉树是否镜像</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">isMirrorBTree</span><span class="params">(BinaryTreeNode root1, BinaryTreeNode root2)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">null</span> == root1 &amp;&amp; <span class="keyword">null</span> == root2) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span> <span class="keyword">if</span>(<span class="keyword">null</span> == root1 || <span class="keyword">null</span> == root2) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(root1.getData() != root2.getData()) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//此处注意相反比较</span></span><br><span class="line">    <span class="keyword">return</span> isMirrorBTree(root1.getLeftChild(),root2.getRightChild())</span><br><span class="line">        &amp;&amp; isMirrorBTree(root1.getRightChild(),root2.getLeftChild());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="判断是否为完全二叉树"><a href="#判断是否为完全二叉树" class="headerlink" title="判断是否为完全二叉树"></a>判断是否为完全二叉树</h4><p>我们可以根据题意做题即可，我们可以采用分层遍历的方式，在判断一个具体的节点的时候，我们可以有如下的判断依据:</p>
<ol>
<li>如果这个节点的左子树为null，右子树不为null，则一定不是完全二叉树</li>
<li>如果这个节点的左右子树均为null，或者这个节点的左子树不为null但是右子树为null，则当前层或者下一层不能再出现含有左右子树的节点</li>
<li>如果当前节点的左右子树均不为null，则观察下一个节点</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isCompleteBTree</span><span class="params">(BinaryTreeNode node)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (node == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">boolean</span> hasLeaf = <span class="keyword">false</span>;</span><br><span class="line">    List&lt;BinaryTreeNode&gt; queue = <span class="keyword">new</span> LinkedList&lt;&gt;();</span><br><span class="line">    queue.offer(node);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span> (!queue.isEmpty()) &#123;</span><br><span class="line">        BinaryTreeNode tmp = queue.poll();</span><br><span class="line">        <span class="keyword">if</span> (tmp.getLeftChild() == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (tmp.getRightChild() != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//情况1，左子树为null，右子树不为null，则一定不是完全二叉树</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (tmp.getRightChild() == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//情况2，左右子树均为null</span></span><br><span class="line">                <span class="comment">//则当前层或者下一层不能再出现含有左右子树的节点</span></span><br><span class="line">                hasLeaf = <span class="keyword">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (hasLeaf) &#123;</span><br><span class="line">                <span class="comment">//出现了含有左子树的节点，直接返回false</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (tmp.getRightChild() == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//情况2，左子树不为null，右子树为null</span></span><br><span class="line">                <span class="comment">//则当前层或者下一层不能再出现含有左右子树的节点</span></span><br><span class="line">                hasLeaf = <span class="keyword">true</span>;</span><br><span class="line">                queue.add(tmp.getLeftChild());</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (tmp.getRight() != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">//情况3，左右子树均不为null，则观察下一个节点</span></span><br><span class="line">                queue.add(tmp.getLeftChild());</span><br><span class="line">                queue.add(tmp.getRightChild());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="翻转二叉树-镜像二叉树"><a href="#翻转二叉树-镜像二叉树" class="headerlink" title="翻转二叉树(镜像二叉树)"></a>翻转二叉树(镜像二叉树)</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> BinaryTreeNode <span class="title">invertTree</span><span class="params">(BinaryTreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (root == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//递归反转左右子树</span></span><br><span class="line">    BinaryTreeNode temp = root.getLeftChild();</span><br><span class="line">    root.getLeftChild() = invertTree(root.getRightChild());</span><br><span class="line">    root.getRightChild() = invertTree(temp);</span><br><span class="line">    <span class="keyword">return</span> root;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="判断是否是二叉查找树"><a href="#判断是否是二叉查找树" class="headerlink" title="判断是否是二叉查找树"></a>判断是否是二叉查找树</h4><p>一棵BST定义为：</p>
<ul>
<li>节点的左子树中的值要严格小于该节点的值</li>
<li>节点的右子树中的值要严格大于该节点的值</li>
<li>左右子树也必须是二叉查找树</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根节点的值data必然在(minVal,maxVal)这个范围内</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isValidBST</span><span class="params">(BinaryTreeNode root, <span class="keyword">long</span> minVal, <span class="keyword">long</span> maxVal)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">null</span> == root) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(root.getData() &gt;= maxVal || root.getData() &lt;= minVal) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> isValidBST(root.getLeftChild(), minVal, root.data)</span><br><span class="line">        &amp;&amp; isValidBST(root.getRightChild(), root.data, maxVal);		</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="判断是否是平衡二叉树"><a href="#判断是否是平衡二叉树" class="headerlink" title="判断是否是平衡二叉树"></a>判断是否是平衡二叉树</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">IsBalancedTree</span><span class="params">(BinaryTreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(root == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//左右子树高度绝对值大于1，返回false</span></span><br><span class="line">    <span class="keyword">if</span>(Math.abs(getMaxDepth(root.getLeftChild())-getMaxDepth(root.getRightChild()))&gt;<span class="number">1</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="comment">//递归检查左右子树</span></span><br><span class="line">        <span class="keyword">return</span> IsBalancedTree(root.getLeftChild()) </span><br><span class="line">            &amp;&amp; IsBalancedTree(root.getRightChild());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//求高度</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMaxDepth</span><span class="params">(BinaryTreeNode root)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(root == <span class="keyword">null</span>)&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> left = getMaxDepth(root.getLeftChild());</span><br><span class="line">    <span class="keyword">int</span> right = getMaxDepth(root.getRightChild());</span><br><span class="line">    <span class="keyword">return</span> left &gt; right ? left + <span class="number">1</span> : right + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yanbing
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E4%BA%8C%E5%8F%89%E6%A0%91/" title="二叉树">http://yoursite.com/2020/05/30/数据结构与算法/二叉树/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/05/30/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E5%9B%BE/" rel="prev" title="图算法">
      <i class="fa fa-chevron-left"></i> 图算法
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/05/30/%E6%95%B0%E6%8D%AE%E5%BA%93/Redis%E4%B8%8E%E7%BC%93%E5%AD%98/" rel="next" title="Redis与缓存">
      Redis与缓存 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的定义"><span class="nav-number">1.</span> <span class="nav-text">二叉树的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的实现"><span class="nav-number">2.</span> <span class="nav-text">二叉树的实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二叉树的操作"><span class="nav-number">3.</span> <span class="nav-text">二叉树的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#遍历"><span class="nav-number">3.1.</span> <span class="nav-text">遍历</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#先根遍历-Pre-Order"><span class="nav-number">3.1.1.</span> <span class="nav-text">先根遍历(Pre Order)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#中根遍历-In-Order"><span class="nav-number">3.1.2.</span> <span class="nav-text">中根遍历(In Order)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#后根遍历-Post-Order"><span class="nav-number">3.1.3.</span> <span class="nav-text">后根遍历(Post Order)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#层次遍历-Level-Traverse"><span class="nav-number">3.1.4.</span> <span class="nav-text">层次遍历(Level Traverse)</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#常用操作"><span class="nav-number">3.2.</span> <span class="nav-text">常用操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#创建"><span class="nav-number">3.2.1.</span> <span class="nav-text">创建</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#清空"><span class="nav-number">3.2.2.</span> <span class="nav-text">清空</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断是否为空"><span class="nav-number">3.2.3.</span> <span class="nav-text">判断是否为空</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#求最大深度-高度"><span class="nav-number">3.2.4.</span> <span class="nav-text">求最大深度(高度)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#求最小深度"><span class="nav-number">3.2.5.</span> <span class="nav-text">求最小深度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#求所有节点数"><span class="nav-number">3.2.6.</span> <span class="nav-text">求所有节点数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#求叶子节点个数"><span class="nav-number">3.2.7.</span> <span class="nav-text">求叶子节点个数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#求第k层节点数"><span class="nav-number">3.2.8.</span> <span class="nav-text">求第k层节点数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#返回某节点的父亲节点"><span class="nav-number">3.2.9.</span> <span class="nav-text">返回某节点的父亲节点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#查找节点"><span class="nav-number">3.2.10.</span> <span class="nav-text">查找节点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断两棵二叉树是否相等"><span class="nav-number">3.2.11.</span> <span class="nav-text">判断两棵二叉树是否相等</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断两棵二叉树是否镜像"><span class="nav-number">3.2.12.</span> <span class="nav-text">判断两棵二叉树是否镜像</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断是否为完全二叉树"><span class="nav-number">3.2.13.</span> <span class="nav-text">判断是否为完全二叉树</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#翻转二叉树-镜像二叉树"><span class="nav-number">3.2.14.</span> <span class="nav-text">翻转二叉树(镜像二叉树)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断是否是二叉查找树"><span class="nav-number">3.2.15.</span> <span class="nav-text">判断是否是二叉查找树</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断是否是平衡二叉树"><span class="nav-number">3.2.16.</span> <span class="nav-text">判断是否是平衡二叉树</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yanbing"
      src="/images/dog.jpg">
  <p class="site-author-name" itemprop="name">yanbing</p>
  <div class="site-description" itemprop="description">闲看庭前花开落，漫随天外云卷舒。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">59</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yanbingzn" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yanbingzn" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/i_silence" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;i_silence" rel="noopener" target="_blank"><i class="fab fa-codiepie fa-fw"></i>CSDN</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="http://www.beian.miit.gov.cn/" rel="noopener" target="_blank">豫ICP备20019377号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yanbing</span>
</div>

<span id="busuanzi_container_site_uv">
  本站访问次数：<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
</span>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













  

  


  
  <script type="text/javascript"
color="0,0,188" opacity='0.5' zIndex="-1" count="120" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</body>
</html>
